<template>
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-default">
                    <div class="panel-heading">a simple casher demo</div>
                    <div class="panel-body">
                        <div class="col-md-8 panel panel-default">
                            <div class="panel-heading">Item List</div>
                            <div class="panel-body">
                                <el-table :data="itemList" ref="itemTable" :border="false" :fit="true" style="width: 100%">
                                    <el-table-column prop="barcode" label="条码" width="130">
                                    </el-table-column>
                                    <el-table-column label="品名">
                                        <template scope="scope">
                                            {{ scope.row.name }}
                                            <el-tag v-for="type in scope.row.discountType" v-if="type>0" type="success">
                                                {{ formatType(type) }}
                                            </el-tag>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="price" label="单价" width="100">
                                    </el-table-column>
                                    <el-table-column label="数量">
                                        <template scope="scope">
                                            <el-input-number v-model="qty[scope.$index]" :min="1" :max="99" size="small" :key="scope.$index"></el-input-number>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="操作" width="120">
                                        <template scope="scope">
                                            <el-button size="small" @click="addToCart(scope.row,qty[scope.$index])">
                                                加入购物车
                                            </el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                        <div class="col-md-4 panel panel-default">
                            <div class="panel-heading">Shopping Cart</div>
                            <div class="panel-body">
                                <el-table :data="cart" ref="cartTable" style="width: 100%">
                                    <el-table-column prop="name" label="品名">
                                    </el-table-column>
                                    <el-table-column label="数量">
                                        <template scope="scope">
                                            <input type="number" min="1" step="1" v-model="scope.row.qty" @change="updateSubtotal(scope.row,scope.$index)" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="subtotal" label="小计">
                                        <template scope="scope">
                                            {{ scope.row.subtotal }}
                                            <el-button type="primary" icon="delete" size="mini" @click="removeFromCart(scope.row,scope.$index)"></el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                                <el-button v-if="checkOutReady" class="pull-right" type="primary" @click="checkOut()">结账</el-button>
                            </div>
                        </div>
                        <div class="col-md-12 panel panel-default">
                            <div class="panel-heading">Checkout</div>
                            <div class="panel-body" v-if="checkOutFinish">
                                <p>***<没名字商店>购物清单***</p>
                                <div v-for="val in cart">
                                    <span>名称：{{ val.name }}</span>
                                    <span> , 数量：{{ val.qty }} {{ val.unit }}</span>
                                    <span> , 单价：{{ val.price.toFixed(2) }} （元）</span>
                                    <span> , 小计：{{ val.subtotal }}</span>
                                    <span v-if="val.discountAmount > 0"> , 节省：{{ val.discountAmount }} （元）</span>
                                </div>
                                <div v-if="freeItemStore.length > 0">
                                    <p>----------------------</p>
                                    <p>买二赠一商品</p>
                                    <div v-for="val in freeItemStore">
                                        <span>名称：{{ val.name }} , </span>
                                        <span>数量：{{ val.freeItemQty }}</span>
                                    </div>
                                </div>
                                <div>
                                    <p>----------------------</p>
                                    <p>总计：{{ grandTotal.toFixed(2) }} （元）</p>
                                    <p v-if="discountAmount > 0">节省：{{ discountAmount.toFixed(2) }} （元）</p>
                                    <p>**********************</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import axios from 'axios';
export default {
    name: 'Casher',
    props: {

        //购物车中的商品条码
        codeStore: {
            type: Array,
            default: function() {
                return [];
            }
        },
        discountTypeName: {
            type: Array,
            default: function() {
                return ['无', '95折', '买2赠1'];
            }
        }
    },
    data() {
        return {
            itemList: [],
            cart: [],
            qty: [],
            freeItemStore:[],
            grandTotal:0,
            discountAmount:0,
            checkOutReady:false,
            checkOutFinish:false
        }
    },
    computed: {
        // grandTotal: function() {
        //     return this.grandTotal.toFixed(2);
        // },
        // discountAmount: function() {
        //     return this.discountAmount.toFixed(2);
        // }
    },
    watch: {

    },
    methods: {
        //格式化优惠信息
        formatType(type) {
            return this.discountTypeName[type];
        },
        //商品列表
        getItemList() {
            var self = this;

            return axios.get('/goods/all')
                .then(function(res) {
                    self.itemList = res.data;
                })
                .catch(function(error) {
                    console.log(error);
                });
        },
        //添加到购物车
        addToCart(row, qty) {
            // console.log(row);
            if (this.codeStore.indexOf(row.barcode) === -1) {
                var newCartRow = [];
                newCartRow['barcode'] = row.barcode;
                newCartRow['name'] = row.name;
                newCartRow['unit'] = row.unit;
                newCartRow['price'] = row.price;
                newCartRow['qty'] = qty;
                newCartRow['discountType'] = row.discountType;
                newCartRow = this.getDiscount(newCartRow);

                this.cart.push(newCartRow);
                // this.$set(this.cart, index, newCartRow);
                this.codeStore.push(newCartRow['barcode']);
                this.checkOutReady = true;
            }
        },
        removeFromCart(row, index) {
            this.codeStore.splice(this.codeStore.indexOf(row.barcode), 1);
            this.cart.splice(index, 1);
            if (this.cart.length == 0) {
                this.checkOutReady = false;
            }
            this.checkOutFinish = false;

        },
        //获取商品小计
        updateSubtotal(row, index) {
            row = this.getDiscount(row);
            // console.log(row);
            this.$set(this.cart, index, row);
            this.checkOutFinish = false;
        },
        //优惠判断
        getDiscount(row) {

            const validDiscount = Math.max.apply(Math, row.discountType);
            row.freeItemQty = 0;
            //
            switch (validDiscount) {
                //无优惠
                case 0:
                    row.subtotal = this.formatPrice(row.price * row.qty)
                    break;
                    //95折
                case 1:
                    row.subtotal = this.formatPrice(row.price * row.qty * 0.95);
                    break;
                    //买2赠1
                case 2:
                    //没有满足 买2赠1 的条件.但可享受 95 折 的情况
                    if (row.qty < 3 && $.inArray(1, row.discountType) !== -1) {
                        row.subtotal = this.formatPrice(row.price * row.qty * 0.95);
                    }
                    // 买2赠1                    
                    else if (row.qty >= 3) {
                        row.subtotal = this.formatPrice(row.price * (Math.floor(row.qty / 3)) * 2 + row.price * (row.qty % 3));
                        //赠送商品的个数
                        row.freeItemQty = Math.floor(row.qty / 3);
                    }
                    //没有满足 买2赠1 的条件
                    else {
                        row.subtotal = this.formatPrice(row.price * row.qty);
                    }

                    break;
            }
            //优惠额度
            row.discountAmount = this.formatPrice(row.price * row.qty - row.subtotal);
            this.checkOutFinish = false;

            return row;
        },
        //结账,输出小票
        checkOut() {
            this.grandTotal = 0;
            this.discountAmount = 0;            
            this.freeItemStore = [];

            for(var i=0;i < this.cart.length; i++) {
                if(this.cart[i].freeItemQty > 0){
                    this.freeItemStore.push(this.cart[i]);
                }
                this.grandTotal += parseFloat(this.cart[i].subtotal);
                this.discountAmount += parseFloat(this.cart[i].discountAmount);
            }
            this.checkOutFinish = true;
        },
        formatPrice(val) {
            return parseFloat(val).toFixed(2);
        }
    },

    mounted() {
        this.getItemList();
    }
}
</script>
<style type="text/css">
input {
    width: 50%;
}

.panel-body {
    padding: 0;
}
</style>
